<template>
  <div class="app-container">
    <Header></Header>
    <Goods
      v-for="item in list"
      :key="item.id"
      :id="item.id"
      :title="item.goods_name"
      :pic="item.goods_img"
      :price="item.goods_price"
      :goods_state="item.goods_state"
      :goods_count="item.goods_count"
      @stateChange="getnewState"
    ><Counter :count="item.goods_count" @num-change="getnum(item, $event)"></Counter>
  </Goods>
 
    <Footer :amout="amt"  :totalCount="totalCount" @set-State="getState" ></Footer>
  </div>
</template>

<script>
import Header from "@/components/Header/Header.vue";
import Goods from "@/components/Goods/Goods.vue";
import Footer from "@/components/Footer/Footer.vue";
import Counter from "@/components/Counter/Counter.vue"

// 导入axios
import axios from "axios";
import bus from "@/components/eventBus.js"

export default {
  data() {
    return {
      list: [],
    };
  },
  components: { Header, Goods },
  methods: {
    async initCarList() {
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      //console.log(res);
      if (res.status === 200) {
        this.list = res.list;
      }
    },
    // e 的值是{ id:this.id, value: changeState }
    getnewState(e) {
      this.list.some((item) => {
        if (item.id === e.id) {
          item.goods_state = e.value;
          return true; // 终止循环
        }
      });
      console.log(e);
    },
    // 接收footer子组件传来的state状态
    getState(e) {
      this.list.forEach((item) => (item.goods_state = e));
      console.log(e);
    },
    // 获取counter最新值
    getnum(item, e){
      item.goods_count = e
    }
  },
  created() {
    // 请求carList数据
    this.initCarList();
    // 接收count传来的数量
    bus.$on('sendCount', (val)=>{
      this.list.some( (item)=>{
        if ( item.id === val.id){
          item.goods_count = val.value
          return true
        }
      } )
    })
  },
  components: {
    Header,
    Goods,
    Footer,
    Counter
  },
  computed: {
    // 全选的状态
    fullState() {
      return this.list.every((item) => item.goods_state === true);
    },
    // 计算价格 已经勾选的商品的总价格
    amt() {
      return this.list
        .filter((item) => item.goods_state === true)
        .reduce((total, item) => {
          return (total += item.goods_price * item.goods_count);
        }, 0);
    },
    // 计算总数量
    totalCount(){
      return this.list.filter(item=> item.goods_state).reduce((t, item)=>{
       return t += item.goods_count
      },0)
    }
  },
};
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
